package com.example.druiddb.config;


import com.example.druiddb.dao.CommonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * TODO   启动时候查看是否有数据表，如果没有，则新建一个数据表
 *
 * @Author xiaojiang
 * @Date 2021/11/24 下午 14:18
 */
@Component
public class MysqlStatus implements ApplicationRunner {

    private final static Logger logger = LoggerFactory.getLogger(MysqlStatus.class);

    @Autowired
    private CommonMapper commonMapper;

    public static MysqlStatus mysqlStatus;

    @PostConstruct
    public void init(){
        mysqlStatus = this;
        mysqlStatus.commonMapper = this.commonMapper;
    }

    @Override
    public void run(ApplicationArguments args){
        logger.info("--- Start checking if the database exists ---");

        Map<String, String> xdm_datasource_documents = mysqlStatus.commonMapper.checkTableExistsWithShow("XDM_DATASOURCE_DOCUMENTS");
        if(CollectionUtils.isEmpty(xdm_datasource_documents)) {
            int i = mysqlStatus.commonMapper.insertDocument();
            if (i == 0)
                logger.info("--- CREATE XDM_DATASOURCE_DOCUMENTS TABLE SUCCESS! ---");
            else
                logger.info("--- CREATE XDM_DATASOURCE_DOCUMENTS TABLE ERROR! ---");
        }else {
            logger.info("--- exist! ---");
        }

    }
}
